package dse.messages.singleversion;

import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;

import dse.DataObject;
import dse.Experiment;
import dse.ExperimentRecorder;
import dse.Node;
import dse.Version;
import dse.messages.Message;
import dse.messages.MessagePurpose;
import dse.messages.MessageUtil;
import dse.messages.Transaction;
import dse.messages.multiversion.VersionReader;

public class GetHen07Transaction extends Transaction implements
		ShareDownloader, VersionReader {
	private DataObject desiredObject;
	private LinkedList<Node> residentNodes;
	private boolean failed;
	private TreeMap<Version, LinkedList<Node>> sharesDownloaded;
	private TreeMap<Version, Integer> candidateVersion;
	private int requestShareCount;
	private int validShareCount;
	private int maxFailure;
	private int successCount;
	private int failureCount;
	private TreeSet<Integer> ts;
	private Version maxVersion;
	private int sharesToBeUpdate;
	private boolean hasRequestPreviousShares;
	private boolean vnf;
	
	public GetHen07Transaction(Experiment experiment,
			int id,
			Node requester,
			DataObject desiredObject,
			double time
			)
	{
		super(id, requester, experiment, time);
		
		this.desiredObject = desiredObject;
		this.failed = false;
		this.requestShareCount = 0;
		this.validShareCount = 0;
		this.maxFailure = experiment.modules().nodeEventScheduler().getEventsPerPeriod();
		this.successCount = 0;
		this.failureCount = 0;
		this.maxVersion = null;
		this.sharesToBeUpdate = desiredObject.shareCount();
		this.hasRequestPreviousShares = false;
		this.vnf = true;
	}

	@Override
	public void start(ExperimentRecorder recorder) {
		// TODO Auto-generated method stub
		residentNodes = MessageUtil.getNodesByDht(experiment.network(), requester, desiredObject, experiment.modules().assigner());		

		if(isUpdate)
		{
			recorder.dataUpdateInitiated(super.id, requester, desiredObject, startTime);
			if(ExperimentRecorder.debug)
				recorder.debug(this, "start", startTime);
			this.requestShareCount = desiredObject.shareCount();
			this.validShareCount = requestShareCount - this.maxFailure;
			
			for (int i=0; (i<requestShareCount) && (i<residentNodes.size()); i++)
				sendShareWritingRequest(recorder, residentNodes.get(i), startTime);
		}
		else
		{
			recorder.dataRequestInitiated(super.id, requester, desiredObject, startTime);
			recorder.debug(this, "start", startTime);
			
			this.requestShareCount = this.desiredObject.requiredShareCount() + 2*this.maxFailure;
			this.validShareCount = desiredObject.requiredShareCount();
			validateRequestShareCount(residentNodes.size());
			for(int i=0; i<requestShareCount; i++)
			{
				sendGetLCVersionRequest(recorder, residentNodes.get(i), startTime);
			}		
		}
	}
	
	private void validateRequestShareCount(int iv){
		if(requestShareCount > iv)
			requestShareCount = iv;
	}
	
	private void sendShareWritingRequest(ExperimentRecorder recorder, Node node, Double time)
	{
		if (node == null) {
			// We should turn this into a warning ...
			recorder.warn(
					"Share assigner failed to map share to node in cluster!"
					);
			return;
		}
		
		Message m = super.createShareUpdateHenMessage(requester, 
				node, desiredObject, MessagePurpose.DataObjectUpdate, this);
		if(ExperimentRecorder.debug)
			recorder.debug(this, "new msg: " + m, time);
		experiment.messageQueue().enqueueMessage(m, time);
	}
	
	private void sendGetLCVersionRequest(ExperimentRecorder recorder, Node node, double time){
		if (node == null) {
			// We should turn this into a warning ...
			recorder.warn(
					"Share assigner failed to map share to node in cluster!"
					);
			return;
		}
		
		Message m = super.createRequestLCVersionMessage(requester, node, desiredObject, 
				MessagePurpose.DataObjectRequest, this);
		if(ExperimentRecorder.debug)
			recorder.debug(this, "new msg: " + m, time);
		experiment.messageQueue().enqueueMessage(m, time);
	}

	@Override
	public Transaction getTransaction(){
		return this;
	}

	@Override
	public void readVersion(ExperimentRecorder recorder,TreeSet<Version> versions, double time, Node from) {}

	@Override
	public void readVersion(ExperimentRecorder recorder, Node from,	Version version, double time) {
		// TODO Auto-generated method stub
		if(failed || finished)
			return;
		
		if(vnf){
			if(version == null){
				failureCount++;
				return;
			}
				
			successCount++;
			if(candidateVersion == null)
				candidateVersion = new TreeMap<Version, Integer>();
			if(candidateVersion.get(version) == null)
				candidateVersion.put(version, 1);
			else
				candidateVersion.put(version, candidateVersion.get(version)+1);
			
			if(successCount + failureCount >= requestShareCount){
				processVersions(recorder, time);			
			}
		}
		else{
			if(version == null){
				failureCount++;
				return;
			}
			
			successCount++;
			if(candidateVersion.get(version) == null)
				candidateVersion.put(version, 1);
			else
				candidateVersion.put(version, candidateVersion.get(version)+1);
		
			if(sharesDownloaded == null)
				sharesDownloaded = new TreeMap<Version, LinkedList<Node>>();
			if(this.sharesDownloaded.get(version) == null)
				this.sharesDownloaded.put(version, new LinkedList<Node>());
			this.sharesDownloaded.get(version).add(from);
			
			if(this.sharesDownloaded.get(version).size() >= validShareCount)
				transactionSucceed(recorder, time);
			else if(successCount + failureCount >= requestShareCount)
				processVersion(recorder, time);
		}
	}
	
	private void processVersion(ExperimentRecorder recorder, double timeLeft)
	{
		if((sharesDownloaded==null) || (sharesDownloaded.size()==0))
		{
			transactionFailed(recorder, timeLeft);
			return;
		}
		
		maxVersion = sharesDownloaded.lastKey();
		if(maxVersion.getSequence()>requester.getSequence())
			requester.setSequence(maxVersion.getSequence());
		Map.Entry<Version, LinkedList<Node>> vn = sharesDownloaded.pollLastEntry();
		while((vn.getValue().size()<validShareCount) && (sharesDownloaded.size()>0))
		{
			vn = sharesDownloaded.pollLastEntry();
		}
		
		if(vn.getValue().size() >= validShareCount)//== requestShareCount)
		{
			transactionSucceed(recorder, timeLeft);
		}
		else if(sharesDownloaded.size() == 0)
		{	
			//int srf = experiment.modules().shareRequestDecisionMaker().sharesToRequestFor(desiredObject)
				//+ this.maxFailure*2;
			if(this.hasRequestPreviousShares)
				recorder.requestPreviousShares(desiredObject, false);
			else{
				this.hasRequestPreviousShares = true;
				recorder.requestPreviousShares(desiredObject, true);
			}
			
			failureCount = 0;
			successCount = 0;
			
			//this.round++;
			this.sharesDownloaded.clear();
			Version v = this.candidateVersion.pollFirstEntry().getKey();
			if(v == null)
				transactionFailed(recorder, timeLeft);
			else{
				for(int i=0; i<this.requestShareCount; i++)
					sendRequestShareWithVersionRequest(recorder, maxVersion, residentNodes.get(i), timeLeft);
			}		
		}
		else
			transactionFailed(recorder, timeLeft);
	}
	
	private void processVersions(ExperimentRecorder recorder, double timeLeft)
	{
		if((candidateVersion==null) || (candidateVersion.size()==0))
		{
			transactionFailed(recorder, timeLeft);
			return;
		}
		
		int count = 0;
		while(candidateVersion.size() > 1){
			count += candidateVersion.firstEntry().getValue();
			if(count >= validShareCount)
				candidateVersion.pollFirstEntry();
		}
		
		maxVersion = candidateVersion.pollFirstEntry().getKey();
		vnf = false;
		successCount = 0;
		failureCount = 0;
		this.requestShareCount = desiredObject.shareCount();
		validateRequestShareCount(residentNodes.size());
		for(int i=0; i<this.requestShareCount; i++)
			sendRequestShareWithVersionRequest(recorder, maxVersion, residentNodes.get(i), timeLeft);
	}
	
	private void sendRequestShareWithVersionRequest(ExperimentRecorder recorder, Version version, Node node, double time){
		if (node == null) {
			// We should turn this into a warning ...
			recorder.warn(
					"Share assigner failed to map share to node in cluster!"
					);
			return;
		}
		
		Message m = super.createRequestShareWithVersionMessage(requester, node, desiredObject, version,
				MessagePurpose.DataObjectRequest, this, false);
		if(ExperimentRecorder.debug)
			recorder.debug(this, "new msg: " + m, time);
		experiment.messageQueue().enqueueMessage(m, time);
	}

	@Override
	public void readVersion(ExperimentRecorder recorder, int seq, double time) {
		// TODO Auto-generated method stub
		if(seq == -1)
		{
			failureCount++;
			return;
		}
		successCount++;
		if(ts == null)
			ts = new TreeSet<Integer>();
		ts.add(seq);
		if(successCount+failureCount >= requestShareCount){
			successCount = 0;
			failureCount = 0;
			if(maxVersion == null)
				maxVersion = new Version(ts.last(), requester.id());
			if(ts.size() > 1){
				ts.clear();
				for(int i=0; i<this.requestShareCount; i++)
					sendVersion(recorder, residentNodes.get(i), maxVersion, time);
			}
			else{	
				for(int i=0; i<this.sharesToBeUpdate; i++)
					sendMAC(recorder, residentNodes.get(i), maxVersion, time);
			}
		}
	}

	@Override
	public void readVersion(ExperimentRecorder recorder, int seq, int index, double time) {	}
	
	private void sendVersion(ExperimentRecorder recorder, Node node, Version v, double time){
		Message m = super.createSendVersionMessage(requester, 
				node, desiredObject, maxVersion, MessagePurpose.DataObjectUpdate, this);
		if(ExperimentRecorder.debug)
			recorder.debug(this, "new msg: " + m, time);
		experiment.messageQueue().enqueueMessage(m, time);
	}
	
	private void sendMAC(ExperimentRecorder recorder, Node node, Version v, double time){
		Message m = super.createSendMACHenMessage(requester, 
				node, desiredObject, maxVersion, MessagePurpose.DataObjectUpdate, this);
		if(ExperimentRecorder.debug)
			recorder.debug(this, "new msg: " + m, time);
		experiment.messageQueue().enqueueMessage(m, time);
	}

	@Override
	public void readVersion(ExperimentRecorder recorder, double time, LinkedList<Version> versions, Version version, Node from) {}

	@Override
	public boolean isDoneDownloadingShares() {
		// TODO Auto-generated method stub
		return (failed || finished);
	}

	@Override
	public boolean isDoneUpdatingShares() {
		// TODO Auto-generated method stub
		return (failed || finished);
	}

	@Override
	public void shareDownloadFailed(ExperimentRecorder recorder, DataObject dobj, int shareIndex, double timeLeft) {}

	@Override
	public void shareDownloaded(ExperimentRecorder recorder, Node from, DataObject dobj, int shareIndex, double timeLeft) {}

	@Override
	public void shareUpdateFailed(ExperimentRecorder recorder, DataObject dobj,
			int shareIndex, double timeLeft) {
		// TODO Auto-generated method stub
		if(isUpdate) {
			this.failureCount++;
			if((successCount + failureCount) >= this.sharesToBeUpdate)
			{
				if(this.successCount >= validShareCount)
					transactionSucceed(recorder, timeLeft);
				else
					transactionFailed(recorder, timeLeft);
			}
		}
	}

	@Override
	public void shareUpdated(ExperimentRecorder recorder, Node to,
			DataObject dobj, int shareIndex, double timeLeft) {
		// TODO Auto-generated method stub
		if(isUpdate) {		
			this.successCount++;
			if((successCount+failureCount) >= this.sharesToBeUpdate)
			{
				if(this.successCount >= validShareCount)
					transactionSucceed(recorder, timeLeft);
				else
					transactionFailed(recorder, timeLeft);
			}
		}
	}
	
	private void transactionSucceed(ExperimentRecorder recorder, double timeLeft)
	{
		finished = true;
		failed  = false;
		//System.out.println("Data ID : " + desiredObject.id() + "Version : " + maxVersion.getSequence() + " , " + maxVersion.getClientID());
		if(isUpdate)
		{
			recorder.debug(
					"GetOSVTransaction trans#" + super.id + 
					" is finshed!!!"
					);
			recorder.dataUpdateFinished(super.id, requester, desiredObject, true, timeLeft);
		}
		else
		{
			recorder.debug(
					"GetOSVTransaction trans#" + super.id + 
					" is finshed!!!"
					);
			recorder.dataRequestFinished(super.id, requester, desiredObject, true, this.residentNodes.get(this.validShareCount-1),
					false, timeLeft);
		}
	}
	
	private void transactionFailed (ExperimentRecorder recorder, double timeLeft)
	{
		recorder.debug(this, "transFailed", timeLeft);
		
		finished = true;
		failed = true;
		if(isUpdate)
			recorder.dataUpdateFinished(super.id, requester, desiredObject, false, timeLeft);
		else{
			recorder.dataRequestFinished(super.id, requester, desiredObject, false, null, false, timeLeft);
		}
	}
}